clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"


cd "${code}/tba_elig"
local flist: dir "${Estimates}" files "embs-lps-Stage*.ster"
foreach f of local flist {
	cap erase "${Estimates}/`f'"
}
local flist: dir "${log}" files "*"
foreach f of local flist {
	cap erase "${log}/`f'"
}

local cmd "sbatch --export=HOME,PATH,SHELL -a 1-216 embs-lps-reg-output.sh" 
di "`cmd'"

local JobIdFile "${log}/job-id.csv"  
log using `JobIdFile', name("jobid") text replace
shell `cmd'
log close _all

do _sbatch-job "`JobIdFile'" 

*** create tables
clear
cd "${code}/tba_elig"
run _esttab-latex-options.do

set obs 1
gen PaboveC = 1
gen Cutoff = 1
gen notba = 1
gen HiP = 1
gen jc = 1

foreach Stage of numlist 1/3 {
	foreach Robust of numlist 6/7 {
		eststo clear

		local mgroup ""
		local pattern ""
		local mtitle ""
		foreach WindowType of numlist 3(-1)1 {
			foreach Poly of numlist 1/3 {
				estimate use "${Estimates}/embs-lps-Stage`Stage'-Window`WindowType'-Poly`Poly'-Robust`Robust'"
				
				quietly {
					eststo
					
					estadd local llpa "Y"
					estadd local Zip "Y"
					estadd local Lender "Y"
					estadd local Month "Y"
					estadd local control "Y"
				}
				if `Poly' == 1 local patternadd = 1
				if `Poly' > 1 local patternadd = 0
				local pattern "`pattern' `patternadd'"
				local mtitle "`mtitle' `"Poly `Poly'"'"
			}
				
			local Min = 417000*1.25 - `WindowType'*50000
			local Max = 417000*1.25 + `WindowType'*50000
			
			local mgroup "`mgroup' `"Home Value $ \in$ [`=substr("`Min'", 1, 3)',`=substr("`Min'", 4, 6)', `=substr("`Max'", 1, 3)',`=substr("`Max'", 4, 6)']"' "
			
		}
		
		if inlist(`Stage', 1, 2) local keepvar "1.HiP#c.PaboveC"
		if inlist(`Stage', 3) {
			if `Robust' <= 3 | `Robust' >= 5 local keepvar "notba"
			if `Robust' == 4 local keepvar "jc"
		}
		
		local fmt "%9.3fc"
		if `Robust' == 4 & `Stage' == 2 local fmt "%9.4fc"
		
		run "${code}/_labels"
		label var HiP "$ 1[z_i>0]$"
							
				
		esttab using "${table}/embs-lps-Stage`Stage'-Robust`Robust'.tex", replace keep(`keepvar') coeflabels(1.HiP#c.PaboveC "$ z_i\times 1[z_i>0]$") ///
		 ${opts_esttab}  b(`fmt') se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) ///
		 stats(llpa Zip Lender Month control N r2_a, fmt(%1s %1s %1s %1s %1s %9.0fc %9.3fc) ///
		 labels("LLPA FE" "Zipcode FE" "Lender FE" "Month FE" "Other Controls" "\midrule N. Obs." "Adj. $ R^2$")) ///
		 mgroup(`mgroup', pattern(`pattern') ${opts_mgroups}) ///
		 mtitle(`mtitle')
		 
	}
}

